package com.ggy.babybed.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;

import org.xclcharts.chart.CustomLineData;
import org.xclcharts.chart.LineChart;
import org.xclcharts.chart.LineData;
import org.xclcharts.common.DensityUtil;
import org.xclcharts.common.IFormatterTextCallBack;
import org.xclcharts.renderer.XEnum;
import org.xclcharts.renderer.plot.PlotGrid;
import org.xclcharts.view.ChartView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by ggy on 2016/6/1.
 */
public class MessageView extends ChartView {

    private final String TAG = "MessageView";

    private LineChart chart = new LineChart();
    private String unit = "";
    //分类轴标签集合
    private List<String> labelsList = new ArrayList<>();
    private LinkedList<String> labels = new LinkedList<>();
    private LinkedList<LineData> chartData = new LinkedList<>();
    private List<Double> datas = new ArrayList<>();
    private List<CustomLineData> mCustomLineDataset = new LinkedList<>();

    public MessageView(Context context) {
        super(context);
    }

    public MessageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MessageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     *
     * @param unit 数据单位标签
     * @param labels 横坐标标签
     * @param datas 数据
     */
    public void initView(String unit, List<String> labels, List<Double> datas) {
        this.labels.clear();
        this.chartData.clear();
        this.mCustomLineDataset.clear();
        this.unit = unit;
        this.labelsList = labels;
        this.datas = datas;
        chartLabels();
        initDataSet();
        chartRender();
    }

    private int[] getPieDefaultSpadding() {
        int[] ltrb = new int[4];
        ltrb[0] = DensityUtil.dip2px(getContext(), 30); //left
        ltrb[1] = DensityUtil.dip2px(getContext(), 60); //top
        ltrb[2] = DensityUtil.dip2px(getContext(), 30); //right
        ltrb[3] = DensityUtil.dip2px(getContext(), 40); //bottom
        return ltrb;
    }

    private void chartRender() {
        try {
            //设置绘图区默认缩进px值
            int[] ltrb = getPieDefaultSpadding();
            float right = DensityUtil.dip2px(getContext(), 10);
            chart.setPadding(ltrb[0], ltrb[1], right, ltrb[3]);

            //标题
            chart.setTitle("环境数据趋势图");
            chart.addSubtitle("(温度 \\ 湿度)");
            chart.getAxisTitle().setLeftTitle(unit);
            chart.getAxisTitle().setLowerTitle("时间(H)");
            chart.getAxisTitle().getLeftTitlePaint().setColor(Color.YELLOW);
            chart.getAxisTitle().getLowerTitlePaint().setColor(Color.YELLOW);
            chart.getPlotTitle().getTitlePaint().setColor(Color.WHITE);
            chart.getPlotTitle().getSubtitlePaint().setColor(Color.WHITE);

            //数据源
            chart.setCategories(labels);
            chart.setDataSource(chartData);
            chart.setCustomLines(mCustomLineDataset);

            chart.getDataAxis().setAxisMax(100);
            chart.getDataAxis().setAxisMin(0);
            chart.getDataAxis().setAxisSteps(10);

            //背景网格
            PlotGrid plot = chart.getPlotGrid();
            plot.hideHorizontalLines();
            plot.hideVerticalLines();
            chart.getDataAxis().getAxisPaint().setColor(Color.rgb(127, 204, 204));
            chart.getCategoryAxis().getAxisPaint().setColor(Color.rgb(127, 204, 204));
            chart.getDataAxis().getTickLabelPaint().setColor(Color.WHITE);
            chart.getCategoryAxis().getTickLabelPaint().setColor(Color.WHITE);
            chart.getDataAxis().getTickMarksPaint().setColor(Color.rgb(127, 204, 204));
            chart.getCategoryAxis().getTickMarksPaint().setColor(Color.rgb(127, 204, 204));

            //定义数据轴标签显示格式
            chart.getDataAxis().setLabelFormatter(new IFormatterTextCallBack(){

                @Override
                public String textFormatter(String value) {
                    Double tmp = Double.parseDouble(value);
                    DecimalFormat df=new DecimalFormat("#0");
                    String label = df.format(tmp).toString();
                    return (label);
                }
            });

            //不使用精确计算，忽略Java计算误差,提高性能
            chart.disableHighPrecision();
            chart.disablePanMode();
            chart.hideBorder();
            chart.getPlotLegend().setType(XEnum.LegendType.COLUMN);
            chart.getCategoryAxis().setLabelLineFeed(XEnum.LabelLineFeed.ODD_EVEN);

        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    private void initDataSet() {
        LinkedList<Double> dataSeries= new LinkedList<>();
        for(Double d : datas){
            dataSeries.add(d);
        }
        LineData lineData = new LineData(unit+"(℃)",dataSeries,Color.rgb(255, 165, 132));
//      lineData.setDotStyle(XEnum.DotStyle.RECT);
        //把线弄细点
        lineData.getLinePaint().setStrokeWidth(4);
//      lineData.getLabelOptions().setLabelBoxStyle(XEnum.LabelBoxStyle.CIRCLE);
//      lineData.getLabelOptions().getBox().getBackgroundPaint().setColor(Color.GREEN);
        lineData.getDotLabelPaint().setTextSize(24);
        lineData.setLineStyle(XEnum.LineStyle.SOLID);
        lineData.setLabelVisible(true);

        chartData.add(lineData);
    }

    private void chartLabels() {
        labels.add("");
        for(String s : labelsList){
            labels.add(s);
        }
    }

    @Override
    public void render(Canvas canvas) {
        try {
            chart.render(canvas);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        chart.setChartRange(w, h);
    }
}
